package cn.virens.web.components.shiro.simple.ajax;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.servlet.AdviceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.web.components.shiro.comm.AjaxUtil;
import cn.virens.web.components.shiro.comm.SessionUtil;

public class AjaxLogoutFilter extends AdviceFilter {
	private Logger logger = LoggerFactory.getLogger(LogoutFilter.class);

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null) return response(request, response);

		// 获取session管理器（不自动创建）,并清空登录缓存信息
		Session session = subject.getSession(false);
		if (session != null) {
			SessionUtil.clearLoginInfo(session);
		}

		// 执行退出登录
		try {
			subject.logout();
		} catch (SessionException ise) {
			logger.debug("Encountered session exception during logout. ", ise);
		}

		// 响应退出结果
		return response(request, response);
	}

	private static boolean response(ServletRequest request, ServletResponse response) {
		return AjaxUtil.write(request, response, AjaxUtil.success("退出成功"));
	}
}
